package com.daxin.controller;

import com.daxin.pojo.User;
import com.daxin.service.UserService;
import com.daxin.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public SysResult register(@RequestBody User user){
        userService.register(user);
        return SysResult.success("ok","注册成功");
    }

    @PostMapping("/login")
    public SysResult login(@RequestBody User user){
        String token = userService.findUserByUP(user);
        System.out.println(token);
        if(StringUtils.hasLength(token)){
            return SysResult.success("登录成功");
        }else {
            return SysResult.fail();
        }
    }

    @GetMapping("/findUser/{id}")
    public SysResult findUser(@PathVariable String id){
        User user = userService.findUserById(id);
        if(user == null){
            return SysResult.fail();
        }else {
            return SysResult.success("ok", user);
        }
    }

    @GetMapping("/hasUsername/{username}")
    public SysResult hasUsername(@PathVariable String username){
        User user = userService.findUserByName(username);
        if(user == null){
            Map<String,Object> info = new HashMap<>();
            info.put("hasUsername",false);
            return SysResult.success("error",info);
        }else {
            Map<String,Object> info = new HashMap<>();
            info.put("hasUsername",true);
            return SysResult.success("ok", info);
        }
    }

    @GetMapping("/hasTel/{tel}")
    public SysResult hasTel(@PathVariable String tel){
        User user = userService.findUserByTel(tel);
        if(user == null){
            Map<String,Object> info = new HashMap<>();
            info.put("hasTel",false);
            return SysResult.success("error", info);
        }else {
            Map<String,Object> info = new HashMap<>();
            info.put("hasTel",true);
            return SysResult.success("ok", info);
        }
    }


}
